from decimal import Decimal
from string import Template
from faker import Faker

import yaml
from jsonpath import jsonpath
from loguru import logger


class Tool:
    @classmethod
    def handle_yaml(cls, file_name):
        """
        读取yaml文件
        :param file_name:
        :return:
        """
        try:
            yaml_data = yaml.safe_load(open(file_name, encoding='utf-8'))
        except Exception as e:
            logger.error(f'yaml文件读取失败，文件名称：{file_name}')
            raise e
        else:
            return yaml_data

    @classmethod
    def handle_token(cls, response):
        """
        组装token
        :param response:
        :return:
        """
        # token_type = jsonpath(response.json(), '$..token_type')[0]
        # token_value = jsonpath(response.json(), '$..access_token')[0]
        token_type = jsonpath(response, '$..token_type')[0].capitalize()
        token_value = jsonpath(response, '$..access_token')[0]
        token = f'{token_type} {token_value}'
        return token

    @classmethod
    def handle_template(cls, source_data, replace_data: dict, ):
        """
        替换文本变量
        :param source_data:
        :param replace_data:
        :return:
        """
        res = Template(str(source_data)).safe_substitute(**replace_data)
        return yaml.safe_load(res)

    @classmethod
    def handle_decimal(cls, data: int):
        """
        将小数或整数转换为两位数decimal
        :param data:
        :return:
        """
        x = '{0:.2f}'.format(float(data))
        return Decimal(x)

    @classmethod
    def handle_random_phone(cls):
        """
        生成随机手机号
        :return:
        """
        fake = Faker(locale='zh_CN')
        phone_number = fake.phone_number()
        return phone_number


if __name__ == '__main__':
    a = Tool.handle_random_phone()
    print(a)
    b = Tool.handle_decimal(6)
    print(b)
    c = Tool.handle_template('$l',{'k':3,'l':2})
    print(c)
    d = Tool.handle_yaml('../conf/config.yaml')
    print(d)
    h = Tool.handle_token({"code": 0, "message": "success", "data": {
        "access_token": "eyJhbGciOiJIUzI1NiIsInppcCI6IkRFRiJ9.eNokjbEKwjAYhN_l5gTa2P6p3QQdHHRQnIzIHxMxUqu0CQjiuxt1O77ju3thTBYt2N1CD4E0-uEYHNpS4D6EX-xT1wn45yNTKqkpiFQtEDj-gVaF-gJO8ZKdGPyYF_cGu-1iYyAMZvPVcm1wyAfXGHJJRXWmhqbSV6RlVbOWVpcTyc5q9kSsToT3BwAA__8.gcDjoy2Pbc3miSThJEvgtXynaflId5z1KYdQ-RhTaxE",
        "token_type": "bearer",
        "refresh_token": "eyJhbGciOiJIUzI1NiIsInppcCI6IkRFRiJ9.eNokjNEKwiAYRt_lv1b43aaz3RtB0cC6F-cmGWvFVAiid8_q7uN8nPOCmAfowI63sACBHKfVhBE6RuC-ht9c8jwTmJ6PQgUTEoWoOIFg0x-0FVZfYHO6FCeFKZai7g_KaLXV6rQz536vjiV_TaFcwtW1t9JRP9aCNhyRDh4lZd61kruNbxDh_QEAAP__.Da3BbMoSEjeHLVvrUiOqofugQEc4Jb1ZttQ7_dEQjOQ",
        "expires_in": 1616806625000, "scope": "scope", "jti": "604f6869-e467-45a7-b713-adb7ae66a2c6"}})
    print(h)